angular.module('CheckTransfer')
    .controller('CheckTransfer.HomeCtrl', ['$q', '$scope', '$state', 'Http', 'imanDialog', 'CheckTransfer.CheckService', 'LfRfid', 'Device', 'Config',
        function($q, $scope, $state, Http, imanDialog, checkService, LfRfid, Device, Config) {
            var toast, localWareHouse = Config.get('wareHouse'),selectWHouseOne;
            //checkService.setContainer();
            if (!angular.isObject(localWareHouse)) {
                localWareHouse = undefined;
            }
            $scope.data = {
                choice: '',
                megs: {},
                wareHouse: localWareHouse ? localWareHouse : { Name: '请选择仓库' }
            };

            $scope.showToast = function(styleMes, block) {
                if (toast) {
                    toast.hide();
                }
                toast = imanDialog.toast({
                    message: styleMes,
                    block: block,
                    position: 'top',
                    duration: false,
                    backdropClickToClose: false,
                    hardwareBackButtonClose: false
                });
            };

            $scope.hideToast = function() {
                if (toast) {
                    toast.hide();
                    toast = null;
                }
            };

            $scope.$on('$ionicView.afterEnter', function() {
                $scope.init();
                $scope.showToast('请先扫描球拍的货架信息', true);
                $scope.data.container = checkService.getContainer();
                LfRfid.open();
                // searchBarcode('0006492131');
            });

            $scope.$on('$ionicView.beforeLeave', function() {
                LfRfid.close();
                $scope.hideToast();
            });

            $scope.$on('LFRFID.DataReceived', function(e, data) {
                searchBarcode(data);
            });

            $scope.beginScan = function() {
                if (!$scope.data.container || ($scope.data.container && !$scope.data.container._id)) {
                    imanDialog.toastBottom("请扫描容器信息");
                    return;
                }

                if ($scope.data.wareHouse.name === '请选择仓库') {
                    imanDialog.toastBottom("请选择超市");
                    return;
                }

                if ($scope.data.choice === '') {
                    imanDialog.toastBottom("请选择需求部门");
                    return;
                }
                checkService.setDepartChoice($scope.data.choice);
                var obj = Config.get('wareHouse');
                if (!angular.isObject(obj)) {
                    obj = {
                        id: ''
                    };
                }
                if ($scope.data.wareHouse._id !== (obj ? obj._id : '')) {
                    Config.set('wareHouse', $scope.data.wareHouse);
                }
                $state.go('CheckTransfer-scan');
            };

            $scope.selectWHouse = function() {
                checkService.queryWHouse().then(function(wareHouseArray) {
                    var typeArr = [],
                        defaultValue;

                    angular.forEach(wareHouseArray, function(wareHouse, key) {
                        if (key === 0) {
                            defaultValue = wareHouse._id;
                        }
                        if (localWareHouse && wareHouse._id === localWareHouse._id) {
                            defaultValue = localWareHouse._id;
                        }
                        if(selectWHouseOne){
                            defaultValue = selectWHouseOne;
                        }
                        typeArr.push({ _id: wareHouse._id, Code: wareHouse.Code, Name: wareHouse.Name });
                    });
                    showList(typeArr, defaultValue);
                }, function() {
                    imanDialog.toastBottom('获取仓库信息失败');
                });
            };

            $scope.init = function() {
                if (localWareHouse && localWareHouse._id) {
                    queryDepartment(localWareHouse._id);
                }
            };

            function searchBarcode(barcode) {
                imanDialog.showLoading();
                checkService.queryBarcodeMaster(barcode).then(function(data) {
                    if (data.BarcodeType === 3) {
                        checkService.queryContainer(data).then(function(info) {
                            $scope.data.container = info;
                            checkService.resetDefault();
                        }).finally(function() {
                            imanDialog.hideLoading();
                        });
                        $scope.hideToast();
                    }
                }).finally(function() {
                    imanDialog.hideLoading();
                });
            }

            function updateDepartmentList(res) {
                $scope.data.megs = {};
                angular.forEach(res, function(obj) {
                    if (!$scope.data.megs.hasOwnProperty(obj.DemandDepartment.Code)) {
                        $scope.data.megs[obj.DemandDepartment.Code] = obj.DemandDepartment;
                    }
                });
            }

            function showList(typeArr, defaultValue) {
                imanDialog.showList({
                    title: '选择仓库',
                    list: typeArr,
                    valueField: '_id',
                    displayField: 'Name',
                    value: defaultValue
                }).then(function(select) {
                    $scope.data.wareHouse = select;
                    selectWHouseOne = select._id;
                    queryDepartment(select._id);
                });
            }

            function queryDepartment(value) {
                var defer = $q.defer();
                checkService.queryDepartment(value).then(function(res) {
                    updateDepartmentList(res);
                    defer.resolve(res);
                }, function(err) {
                    imanDialog.toastBottom("获取部门信息失败");
                    defer.reject(err);
                });
                return defer.promise;
            }
        }
    ]);
